package com.zzyk.main.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class FTPUtils {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private FTPClient ftpClient;

    private String address;
    private int port;
    private String username;
    private String password;

    public FTPUtils(@Value("${ftp.address}") String address,
                    @Value("${ftp.port}") int port,
                    @Value("${ftp.username}") String username,
                    @Value("${ftp.password}") String password) {
        log.info("初始化FTP客户");
        this.ftpClient = new FTPClient();
        this.ftpClient.setControlEncoding("UTF-8");
        this.address = address;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    private void conn() throws IOException {
        log.info("尝试连接服务器{}", address);
        this.ftpClient.connect(address, port);
        if (this.ftpClient.isConnected()) {
            log.info("已连接到FTP服务器");
        } else {
            log.error("无法连接到FTP服务器");
        }
    }

    public boolean upload(File file, String filename, String directory) throws IOException {
        InputStream in = new FileInputStream(file);
        return upload(in, filename, directory);
    }

    public boolean upload(InputStream in, String filename, String directory) throws IOException {
        conn();
        this.ftpClient.login(username, password);
        if (FTPReply.isPositiveCompletion(this.ftpClient.getReplyCode())) {
            log.info("用户认证成功");
            ftpClient.enterLocalPassiveMode();
        } else {
            log.error("用户认证失败");
        }
        try {
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (directory != null && !"".equals(directory)) {
                ftpClient.changeWorkingDirectory(directory);
            }
            ftpClient.storeFile(filename, in);
            return true;
        } catch (IOException e) {
            log.error("上传文件出错", e);
            return false;
        } finally {
            ftpClient.logout();
        }
    }
}
